// class-manage.js
// 移除对 utils.js 的导入
import { editProfile,logout } from "./auth.js";
window.editProfile = editProfile;
window.logout = logout;
// 页面加载完成后获取并显示班级列表
import {createClass, closeCreateClassModal,saveClass} from './class.js';
window.createClass = createClass;
window.closeCreateClassModal = closeCreateClassModal;
window.saveClass = saveClass;
document.addEventListener('DOMContentLoaded', async () => {
    const urlParams = new URLSearchParams(window.location.search);
    const username = urlParams.get('username');
    
    if (!username) {
        alert('用户信息缺失，请重新登录');
        window.location.href = 'login.html';
        return;
    }
    await setupUserProfile(username);
    try {
        const userResponse = await fetch(`/user-info?username=${escapeHTML(username)}`);
        const userData = await userResponse.json();
        
        if (userData.role !== '教师') {
            alert('该功能为教师专属');
            window.location.href = 'success.html?username=' + username;
            return;
        }
        
        // 获取教师创建的班级
        const classesResponse = await fetch(`/get-teacher-classes?teacherUserId=${escapeHTML(userData.user_id)}`);
        const classes = await classesResponse.json();
        
        const classesContainer = document.getElementById('classesContainer');
        
        if (classes.length === 0) {
            classesContainer.innerHTML = '<p class="no-content-message">暂无班级</p>';
        } else {
            for(const classInfo of classes) {
                const response = await fetch(`/get-class-members?classCode=${escapeHTML(classInfo.class_code)}`);
                const members = await response.json();
                const student_count = members.length;
    const classBox = document.createElement('div');
    classBox.classList.add('class-card'); // 添加class-card类
    classBox.innerHTML = `
    <div class="class-card-header flex items-start justify-between mb-4">
        <div>
            <h3 class="text-lg font-semibold text-gray-800 truncate max-w-[200px]">
                <i class="fas fa-chalkboard-teacher text-blue-500 mr-2"></i>
                ${escapeHTML(classInfo.class_name)}
            </h3>
            <p class="text-sm text-gray-500 mt-1">
                <i class="fas fa-hashtag text-gray-400 mr-1"></i>
                班级编号: ${escapeHTML(classInfo.class_code)}
            </p>
        </div>
        <span class="bg-blue-100 text-blue-800 text-xs font-medium px-2.5 py-0.5 rounded-full">
            ${student_count || 0}人
        </span>
    </div>
    
    <div class="class-card-actions flex flex-col sm:flex-row gap-2 mt-4">
        <button 
            onclick="viewClassMembers('${escapeHTML(classInfo.class_code)}', '${escapeHTML(classInfo.class_name)}')" 
            class="btn-action btn-view-members flex-1">
            <i class="fas fa-users mr-2"></i>查看成员
        </button>
        <button 
            onclick="openImportMembersModal('${escapeHTML(classInfo.class_code)}')" 
            class="btn-action btn-import flex-1">
            <i class="fas fa-file-import mr-2"></i>导入名单
        </button>
        <button 
            onclick="deleteClass('${escapeHTML(classInfo.class_code)}', this)" 
            class="btn-action btn-delete flex-1 bg-red-500 hover:bg-red-600 text-white">
            <i class="fas fa-trash-alt mr-2"></i>删除班级
        </button>
    </div>
`;
    classesContainer.appendChild(classBox);
}
        }
    } catch (error) {
        console.error('获取班级信息失败:', error);
        alert('获取班级信息失败，请稍后重试');
    }
});

// 查看班级成员
window.viewClassMembers = async function(classCode, className) {
    try {
        const response = await fetch(`/get-class-members?classCode=${escapeHTML(classCode)}`);
        const members = await response.json();
        //console.log(members);
        const membersBody = document.getElementById('classMembersBody');
        membersBody.innerHTML = '';
        
        if (members.length === 0) {
            membersBody.innerHTML = '<tr><td colspan="4" class="no-content-message">暂无成员</td></tr>'; // 修改colspan为4
        } else {
            for (const member of members) {
                const row = document.createElement('tr');
                const urlParams = new URLSearchParams(window.location.search);
                const username = urlParams.get('username');
                const userResponse = await fetch(`/user-info?username=${escapeHTML(username)}`);
                const userData = await userResponse.json();
                const userId = member.user_id;

                // 获取用户选择的课程
                const courses = await getCourses(member.username);
                let practiceIds = [];
                for (const course of courses) {
                    const practices = await getPracticesByCourse(course.course_code);
                    practiceIds = practiceIds.concat(practices.map(p => p.practice_id));
                }

                let submittedCount = 0;
                for (const practiceId of practiceIds) {
                    const submissionCheckRes = await fetch(`/check-submission?userId=${escapeHTML(userId)}&practiceId=${escapeHTML(practiceId)}`);
                    const submissionCheckData = await submissionCheckRes.json();
                    if (submissionCheckData.hasSubmission) {
                        submittedCount++;
                    }
                }

                const totalCount = practiceIds.length;
                const ratio = totalCount > 0 ? (submittedCount / totalCount) * 100 : 0;

                row.innerHTML = `
                    <td>${escapeHTML(member.student_id)}</td>
                    <td>${escapeHTML(member.name)}</td>
                    <td>
    <div class="progress-container" style="display: flex; align-items: center;">
        <div class="bg-gray-200 rounded-full h-2.5 mr-2 w-full">
            <div class="bg-blue-600 h-2.5 rounded-full" style="width: ${ratio}%;"></div>
        </div>
        <span>${submittedCount}/${totalCount}</span>
    </div>
</td>
                    <td class="text-center">
    <button onclick="removeMember('${escapeHTML(classCode)}', '${escapeHTML(member.user_id)}', this)" 
        class="btn btn-outline btn-hover bg-red-500 text-white hover:bg-red-600 transition-colors">
        <i class="fas fa-user-minus mr-2"></i>移除
    </button>
</td>
                `;
                membersBody.appendChild(row);
            }
        }
        
        document.getElementById('classNameHeader').textContent = `${escapeHTML(className)} - 班级成员`;
        document.getElementById('classMembersModal').style.display = 'flex';
        document.getElementById('classMembersModal').classList.add('active');
        document.body.style.overflow = 'hidden';
    } catch (error) {
        console.error('获取班级成员失败:', error);
        alert('获取班级成员失败，请稍后重试');
    }
};

// 获取用户已选课程
async function getCourses(username) {
    const response = await fetch(`/get-selected-courses?username=${escapeHTML(username)}`);
    const courses = await response.json();
    return courses;
}

// 新增获取课程对应的练习的接口
async function getPracticesByCourse(courseCode) {
    const response = await fetch(`/practice/course/${escapeHTML(courseCode)}`);
    return await response.json();
}

// 移除班级成员
window.removeMember = async function(classCode, userId, button) {
    if (confirm('确定要移除该成员吗？')) {
        try {
            const response = await fetch(`/remove-class-member`, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify({
                    classCode,
                    userId
                })
            });
            
            const result = await response.json();
            if (result.success) {
                alert('移除成功');
                // 从表格中删除该行
                const row = button.closest('tr');
                row.remove();
                
                // 如果表格为空，显示空消息
                const membersBody = document.getElementById('classMembersBody');
                if (membersBody.children.length === 0) {
                    membersBody.innerHTML = '<tr><td colspan="3" class="no-content-message">暂无成员</td></tr>';
                }
            } else {
                alert(result.message || '移除失败');
            }
        } catch (error) {
            console.error('移除成员失败:', error);
            alert('移除成员失败，请稍后重试');
        }
    }
};

// 关闭班级成员模态框
window.closeClassMembersModal = function() {
    document.getElementById('classMembersModal').style.display = 'none';
    document.getElementById('classMembersModal').classList.remove('active');
    document.body.style.overflow = '';
};

// 返回上一页
window.goBack = function() {
    window.history.back();
};

// 打开导入成员名单模态框
window.openImportMembersModal = function(classCode) {
    //console.log('openImportMembersModal');
    document.getElementById('importClassCode').value = classCode;
    document.getElementById('importMembersModal').style.display = 'flex';
    document.getElementById('importMembersModal').classList.add('active');
    document.body.style.overflow = 'hidden';
};

// 关闭导入成员名单模态框
window.closeImportMembersModal = function() {
    document.getElementById('importMembersModal').style.display = 'none';
    document.getElementById('importMembersModal').classList.remove('active');
    document.body.style.overflow = '';
    
    document.getElementById('importFile').value = ''; // 清空文件选择
};

window.importMembers = async function() {
    const classCode = document.getElementById('importClassCode').value;
    const fileInput = document.getElementById('importFile');
    const file = fileInput.files[0];
    
    if (!file) {
        alert('请选择要上传的文件');
        return;
    }
    
    // 检查文件类型
    if (file.name.split('.').pop().toLowerCase() !== 'xlsx') {
        alert('仅支持.xlsx格式的文件');
        return;
    }
    
    try {
        const formData = new FormData();
        formData.append('classCode', classCode);
        formData.append('file', file);
        
        const response = await fetch('/import-class-members', {
            method: 'POST',
            body: formData
        });
        
        const result = await response.json();
        alert(result.message);
        closeImportMembersModal();
    } catch (error) {
        console.error('导入成员失败:', error);
        alert('导入成员失败，请稍后重试');
    }
};

// 打开导入帮助模态框
window.openImportHelpModal = function() {
    document.getElementById('importHelpModal').style.display = 'flex';
    document.getElementById('importHelpModal').classList.add('active');
    document.body.style.overflow = 'hidden';
};

// 关闭导入帮助模态框
window.closeImportHelpModal = function() {
    document.getElementById('importHelpModal').style.display = 'none';
    document.getElementById('importHelpModal').classList.remove('active');
    document.body.style.overflow = '';
};

window.deleteClass = async function(classCode, button) {
    if (confirm('确定要删除这个班级吗？此操作将同时删除所有班级成员有关此班级的信息，且不可恢复！')) {
        try {
            const response = await fetch('/delete-class', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify({
                    classCode
                })
            });
            
            const result = await response.json();
            if (result.success) {
                alert('班级删除成功');
                // 移除班级卡片
                const classCard = button.closest('.class-card');
                classCard.remove();
                
                // 如果所有班级都被删除了，显示空消息
                const classesContainer = document.getElementById('classesContainer');
                if (classesContainer.children.length === 0) {
                    classesContainer.innerHTML = '<p class="no-content-message">暂无班级</p>';
                }
            } else {
                alert(result.message || '删除班级失败');
            }
        } catch (error) {
            console.error('删除班级失败:', error);
            alert('删除班级失败，请稍后重试');
        }
    }
};

async function setupUserProfile(username) {
    try {
        // 1. 获取用户信息
        const response = await fetch(`/user-info?username=${escapeHTML(username)}`);
        if (!response.ok) throw new Error('获取用户信息失败');
        
        const userInfo = await response.json();
        
        // 2. 显示用户信息
        const userInfoContainer = document.getElementById('user-info-container');
        const userNameElement = document.getElementById('user-name');
        const studentIdElement = document.getElementById('student-id');
        
        userNameElement.textContent = userInfo.name || username;
        studentIdElement.textContent = userInfo.student_id || '学号未设置';
        userInfoContainer.classList.remove('hidden');
        
        // 3. 设置头像点击事件
        const userAvatar = document.getElementById('user-avatar');
        const dropdownMenu = document.getElementById('user-dropdown');
        
        userAvatar.addEventListener('click', function(e) {
            e.preventDefault();
            dropdownMenu.classList.toggle('hidden');
        });
        
        // 点击页面其他区域关闭下拉菜单
        document.addEventListener('click', function(e) {
            if (!userAvatar.contains(e.target) && !dropdownMenu.contains(e.target)) {
                dropdownMenu.classList.add('hidden');
            }
        });
    } catch (error) {
        console.error('设置用户信息失败:', error);
        // 错误处理：如果获取信息失败，至少显示用户名
        const userInfoContainer = document.getElementById('user-info-container');
        const userNameElement = document.getElementById('user-name');
        
        if (userInfoContainer && userNameElement) {
            userNameElement.textContent = username;
            userInfoContainer.classList.remove('hidden');
        }
    }
}

document.addEventListener('DOMContentLoaded', function() {
    // 获取"返回"链接元素
    const backLink = document.querySelector('ul.flex li:first-child a');
    if (backLink) {
        // 添加点击事件监听器
        backLink.addEventListener('click', function(event) {
            event.preventDefault(); 
            window.location.href ='success.html'+window.location.search;
        });
    }
});

function escapeHTML(str) {
    return str.replace(/[&<>"']/g, function (match) {
    switch (match) {
    case '&':
    return '&amp;';
    case '<':
    return '&lt;';
    case '>':
    return '&gt;';
    case '"':
    return '&quot;';
    case "'":
    return '&#039;';
}
 });
}